/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.gitee.huangjianbo.supos.openapi.core.tools;

/**
 * 十六进制工具类
 * 
 * @author tomcat
 * @version 1.0
 */
public final class HexUtils {

    private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    /**
     * 将字节数组转换为十六进制字符串
     * 
     * @param data 字节数组 
     * @return 十六进制字符串
     */
    public static String encodeHexString(final byte[] data) {
        return new String(encodeHex(data));
    }

    /**
     * 将字节数组转换为十六进制字符数组
     * 
     * @param data 字节数组
     * @return 十六进制字符数组
     */
    public static char[] encodeHex(final byte[] data) {
        return encodeHex(data, true);
    }

    /**
     *  将字节数组转换为十六进制字符数组
     * 
     * @param data 字节数组
     * @param toLowerCase 是否转换为小写
     * @return 十六进制字符数组
     */
    public static char[] encodeHex(final byte[] data, final boolean toLowerCase) {
        return encodeHex(data, toAlphabet(toLowerCase));
    }

    /**
     * 将字节数组转换为十六进制字符数组
     * 
     * @param data 字节数组
     * @param toDigits 填充字符数组
     * @return 十六进制字符数组
     */
    public static char[] encodeHex(final byte[] data, final char[] toDigits) {
        final int dataLength = data.length;
        return encodeHex(data, dataLength, toDigits, new char[dataLength << 1]);
    }

    /**
     *  将字节数组转换为十六进制字符数组
     * 
     * @param data
     * @param dataLen
     * @param toDigits
     * @param out
     * @return
     */
    private static char[] encodeHex(final byte[] data, final int dataLen, final char[] toDigits, final char[] out) {
        for (int i = 0, j = 0; i < dataLen; i++) {
            out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
            out[j++] = toDigits[0x0F & data[i]];
        }
        return out;
    }

    /**
     * 将十六进制字符转换成字节数组
     * 
     * @param toLowerCase
     * @return
     */
    private static char[] toAlphabet(final boolean toLowerCase) {
        return toLowerCase ? DIGITS_LOWER : DIGITS_UPPER;
    }
}
